package com.zmx.patients.fragment.friends;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.app.SharedElementCallback;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zmx.patients.R;
import com.zmx.patients.adapter.FriendsItemAdapter;
import com.zmx.patients.adapter.base.BaseHelper;
import com.zmx.patients.listener.OnItemPictureClickListener;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.FriendsMessage;
import com.zmx.patients.pojo.Give;
import com.zmx.patients.utils.P;
import com.zmx.patients.utils.Utils;
import com.zmx.patients.view.activity.ImagePreviewActivity;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FocusOnFragment  extends Fragment {

    private RecyclerView recyclerView;
    private FriendsItemAdapter adapter;
    private List<FriendsMessage> girlList;
    private Bundle mReenterState;
    private int itemPosition;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_recommended, container, false);
        girlList = new ArrayList<>();
        recyclerView = view.findViewById(R.id.recyclerView);
        initShareElement();
        bbsList();
        return view;

    }

    private void initShareElement() {
        this.getActivity().setExitSharedElementCallback(mCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mReenterState = new Bundle(data.getExtras());
        int startingPosition = mReenterState.getInt(P.CURRENT_ITEM_POSITION);
        if (startingPosition != itemPosition) {//如果不是同一个item就滚动到指定的item
            recyclerView.scrollToPosition(itemPosition);
        }
        postponeEnterTransition();
        recyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
                recyclerView.requestLayout();
                startPostponedEnterTransition();
                return true;
            }
        });
    }

    private final SharedElementCallback mCallback = new SharedElementCallback() {

        @Override
        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
            if (mReenterState != null) {
                //从别的界面返回当前界面
                int startingPosition = mReenterState.getInt(P.START_IAMGE_POSITION);
                int currentPosition = mReenterState.getInt(P.CURRENT_IAMGE_POSITION);
                if (startingPosition != currentPosition) {//如果不是之前的那张图片就切换到指定的图片
                    String newTransitionName = Utils.getNameByPosition(itemPosition,currentPosition);
                    View view = recyclerView.findViewWithTag(newTransitionName);
                    if (view != null) {
                        names.clear();
                        names.add(newTransitionName);
                        sharedElements.clear();
                        sharedElements.put(newTransitionName, view);
                    }
                }
                mReenterState = null;
            }
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:
                    Log.e("数据","数据"+msg.obj.toString());

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        if (object.getInt("code")==1){

                            JSONArray array = object.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0;i<array.length();i++){

                                JSONObject data = array.getJSONObject(i);
                                FriendsMessage fm = gson.fromJson(data.toString(),FriendsMessage.class);

                                JSONArray imgs = data.getJSONArray("picture");
                                List<String> imageList = new ArrayList<>();
                                for (int j=0;j<imgs.length();j++){

                                    Log.e("图片路径","图片路径"+imgs.get(j).toString());
                                    imageList.add(imgs.get(j).toString());

                                }
                                JSONArray imgs_live = data.getJSONArray("give");
                                List<Give> lives = new ArrayList<>();
                                for (int g=0;g<imgs_live.length();g++){

                                    Give give = gson.fromJson(imgs_live.getJSONObject(g).toString(),Give.class);
                                    lives.add(give);

                                }

                                fm.setGives(lives);
                                fm.setPicture(imageList);
                                girlList.add(fm);
                            }

                            adapter = new FriendsItemAdapter(FocusOnFragment.this.getContext(), girlList, new OnItemPictureClickListener() {
                                @Override
                                public void onItemPictureClick(int item,int position, String url, List<String> urlList, ImageView imageView) {
                                    itemPosition = item;
                                    Intent intent = new Intent(FocusOnFragment.this.getContext(), ImagePreviewActivity.class);
                                    intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
                                    intent.putExtra(P.START_ITEM_POSITION, itemPosition);
                                    intent.putExtra(P.START_IAMGE_POSITION, position);
                                    ActivityOptions compat = ActivityOptions.makeSceneTransitionAnimation(FocusOnFragment.this.getActivity(), imageView, imageView.getTransitionName());
                                    startActivity(intent, compat.toBundle());
                                }
                            });
                            BaseHelper.setLinearLayoutManagerVertical(FocusOnFragment.this.getContext(),recyclerView,adapter);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }

        }
    };


    public void bbsList() {


        Map<String, Object> params = new HashMap<String, Object>();
        params.put("cmd", "bbsList");
        params.put("data[sort]", "pubtime");
        params.put("data[row]",1+"");
        params.put("data[member_id]", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("data[number]",10+"");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.bbs/bbsList", params, handler, 1, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }

}
